package com.yxw.yxnet_cd_center.customer_service.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.CommonErrorEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.customer_service.dto.CustomOperateDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.CustomOperateQueryDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.ProductQueryDTO;
import com.yxw.yxnet_cd_center.customer_service.entity.*;
import com.yxw.yxnet_cd_center.customer_service.mapper.CustomOperateMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.OperatePushRecordMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.RelevancyMapper;
import com.yxw.yxnet_cd_center.customer_service.service.ICustomOperateService;
import com.yxw.yxnet_cd_center.customer_service.utils.PageUtils;
import com.yxw.yxnet_cd_center.customer_service.vo.CustomOperateVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

import static com.yxw.yxnet_cd_center.customer_service.mapper.CustomOperateMapper.*;

/**
 * 客户管理Service业务层处理
 *
 * @author xiexuxin
 * @date 2023-09-24
 */
@Slf4j
@Service
public class CustomOperateServiceImpl extends ServiceImpl<CustomOperateMapper, YxCsCustomOperateEntity> implements ICustomOperateService {

    @Autowired
    private CustomOperateMapper operateMapper;

    @Autowired
    private RelevancyMapper relevancyMapper;

    @Autowired
    private OperatePushRecordMapper recordMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCustomOperate(CustomOperateDTO operateDTO) {
        log.info("开始处理新建运营项目的业务，参数：{}", operateDTO);
        // 创建运营项目实体对象并复制属性值
        YxCsCustomOperateEntity operate = new YxCsCustomOperateEntity();
        BeanUtils.copyProperties(operateDTO, operate);
        // 设置选择类型、运营模式和推送方式对应的名称
        String chooseType = CHOOSE_TYPE[Math.toIntExact(operateDTO.getChooseType())];
        operate.setChooseTypeName(chooseType);
        String operateMode = OPERATE_MODE[Math.toIntExact(operateDTO.getOperateMode())];
        operate.setOperateModeName(operateMode);
        String pushMode = PUSH_MODE[Math.toIntExact(operateDTO.getPushMode())];
        if (operateDTO.getPushMode()==1){
            operate.setPushTime(operateDTO.getPushTime());
        }
        operate.setPushModeName(pushMode);
        // 设置运营项目的初始状态和创建时间
        String operateStatus = OPERATE_STATUS[0];
        operate.setOperateStatusName(operateStatus);
        operate.setOperateStatus(0L);
        operate.setCreateTime(LocalDateTime.now());
        // 添加运营项目数据
        int rows = operateMapper.insert(operate);
        if (rows != 1) {
            throw new BaseException(CommonErrorEnum.INSERT_ERROR,"添加运营项目失败，服务器忙，请稍后再尝试！");
        }
        // 关联运营项目与商品数据
        List<Long> productIds = operateDTO.getProductIds();
        List<YxCsOperateProductEntity> operateProductList = new ArrayList<>();
        for (Long productId : productIds) {
            YxCsOperateProductEntity operateProduct = new YxCsOperateProductEntity();
            operateProduct.setOperateId(operate.getOperateId());
            operateProduct.setProductId(productId);
            operateProductList.add(operateProduct);
        }
        rows = operateMapper.insertOperateProductBatch(operateProductList);
        if (rows < 1) {
            throw new BaseException(CommonErrorEnum.INSERT_ERROR, "关联运营推送商品失败，服务器忙，请稍后再尝试！");
        }
        // 关联运营项目与客户数据
        List<Long> custIds = operateDTO.getCustIds();
        List<YxCsOperateCustEntity> operateCustList = new ArrayList<>();
        for (Long custId : custIds) {
            YxCsOperateCustEntity operateCust = new YxCsOperateCustEntity();
            operateCust.setOperateId(operate.getOperateId());
            operateCust.setCustId(custId);
            operateCustList.add(operateCust);
        }
        rows = operateMapper.insertOperateCustBatch(operateCustList);
        if (rows < 1) {
            throw new BaseException(CommonErrorEnum.INSERT_ERROR,  "关联运营与客户失败，服务器忙，请稍后再尝试！");
        }
        // 关联运营项目与标签数据
        List<Long> tagIds = operateDTO.getTagIds();
        List<YxCsOperateTagEntity> operateTagList = new ArrayList<>();
        for (Long tagId : tagIds) {
            YxCsOperateTagEntity operateTag = new YxCsOperateTagEntity();
            operateTag.setDictCode(tagId);
            operateTag.setOperateId(operate.getOperateId());
            operateTagList.add(operateTag);
        }
        rows = operateMapper.insertOperateTagBatch(operateTagList);
        if (rows < 1) {
            throw new BaseException(CommonErrorEnum.INSERT_ERROR, "关联运营标签失败，服务器忙，请稍后再尝试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByOperateId(Long operateId) {
        log.info("开始处理【删除运营项目数据】的业务，参数：{}", operateId);
        // 查询运营项目是否存在
        CustomOperateVO queryResult =operateMapper.selectOperateById(operateId);
        // 删除关联数据
        relevancyMapper.deleteOperateCustByOperateId(operateId);
        relevancyMapper.deleteOperateProductByOperateId(operateId);
        relevancyMapper.deleteOperateTagByOperateId(operateId);
        // 检查运营项目是否存在
        if (queryResult == null || queryResult.getOperateId() == 0) {
            throw new BaseException(CommonErrorEnum.DATA_NOT_EXISTED_EXCEPTION,"删除运营项目数据失败，尝试删除的运营项目数据不存在！");
        }
        // 删除运营项目数据
        int rows = operateMapper.deleteByOperateId(operateId);
        // 检查删除是否成功
        if (rows != 1) {
            throw new BaseException(CommonErrorEnum.DELETE_FILE_ERROR,"删除运营项目数据失败，服务器忙，请稍后再试！");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByOperateIds(List<Long> operateIds) {
        log.info("开始处理【批量删除运营项目数据】的业务，参数：{}", operateIds);
        // 检查参数是否为空
        if (operateIds != null && !operateIds.isEmpty()) {
            throw new BaseException(CommonErrorEnum.DATA_NOT_EXISTED_EXCEPTION, "删除运营项目数据失败，尝试删除的运营项目数据不存在！");
        }
        // 删除关联数据
        for (Long operateId : operateIds) {
            relevancyMapper.deleteOperateCustByOperateId(operateId);
            relevancyMapper.deleteOperateProductByOperateId(operateId);
            relevancyMapper.deleteOperateTagByOperateId(operateId);
        }
        // 批量删除运营项目数据
        int rows = operateMapper.deleteByOperateIds(operateIds);
        // 检查删除是否成功
        if (rows != operateIds.size()) {
            throw new BaseException(CommonErrorEnum.DELETE_FILE_ERROR, "删除运营项目数据失败，服务器忙，请稍后再试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOperate(Long operateId, CustomOperateDTO operateDTO) {
        log.info("开始处理【修改运营项目数据】的业务，参数：{}", operateDTO);
        // 检查运营项目是否存在
        CustomOperateVO queryResult = operateMapper.selectOperateById(operateId);
        if (queryResult == null || queryResult.getOperateId() == 0) {
            throw new BaseException(CommonErrorEnum.DATA_NOT_EXISTED_EXCEPTION, "修改运营项目数据失败，尝试修改的运营项目数据不存在！");
        }
        // 将DTO转换为实体对象
        YxCsCustomOperateEntity customOperate = new YxCsCustomOperateEntity();
        BeanUtils.copyProperties(operateDTO, customOperate);
        // 设置其他属性
        String chooseType = CHOOSE_TYPE[Math.toIntExact(operateDTO.getChooseType())];
        customOperate.setChooseTypeName(chooseType);
        String operateMode = OPERATE_MODE[Math.toIntExact(operateDTO.getOperateMode())];
        customOperate.setOperateModeName(operateMode);
        String pushMode = PUSH_MODE[Math.toIntExact(operateDTO.getPushMode())];
        if (operateDTO.getPushMode() == 1) {
            customOperate.setPushTime(operateDTO.getPushTime());
        }
        customOperate.setPushModeName(pushMode);
        customOperate.setOperateId(operateId);
        customOperate.setUpdateTime(LocalDateTime.now());
        // 更新运营项目
        int rows = updateCustomOperate(customOperate);
        if (rows != 1) {
            throw new BaseException(CommonErrorEnum.UPDATE_ERROR, "修改运营项目数据失败，服务器忙，请稍后再试！");
        }
        // 更新关联信息
        updateOperateTag(operateId, operateDTO.getTagIds());
        updateOperateCust(operateId, operateDTO.getCustIds());
        updateOperateProduct(operateId, operateDTO.getProductIds());
    }

    // 更新运营项目数据
    private int updateCustomOperate(YxCsCustomOperateEntity customOperate) {
        return operateMapper.updateById(customOperate);
    }
    // 更新运营项目和标签的关联关系
    private void updateOperateTag(Long operateId, List<Long> tagIds) {
        relevancyMapper.deleteOperateTagByOperateId(operateId);
        tagIds.stream().forEach(tagId -> relevancyMapper.insertOperateTag(tagId, operateId));
    }
    // 更新运营项目和客户的关联关系
    private void updateOperateCust(Long operateId, List<Long> custIds) {
        relevancyMapper.deleteOperateCustByOperateId(operateId);
        custIds.stream().forEach(custId -> relevancyMapper.insertOperateCust(operateId, custId));
    }
    // 更新运营项目和产品的关联关系
    private void updateOperateProduct(Long operateId, List<Long> productIds) {
        relevancyMapper.deleteOperateProductByOperateId(operateId);
        productIds.stream().forEach(productId -> relevancyMapper.insertOperateProduct(productId, operateId));
    }

    @Override
    public CustomOperateVO selectOperateById(Long operateId) {
        log.info("开始处理【根据id查询运营项目数据】的业务，参数：{}",operateId);
        return operateMapper.selectOperateById(operateId);
    }

    @Override
    public List<CustomOperateVO> operateList() {
        log.info("开始处理【查询运营项目数据列表】的业务，无参数");
        return operateMapper.operateList();
    }

    @Override
    public PageVO<CustomOperateVO> getOperateList(CustomOperateQueryDTO operateQueryDTO) {
        log.info("开始处理【条件查询运营项目数据列表】的业务，条件参数：{}", operateQueryDTO);
        Page<CustomOperateVO> page = new Page<>(operateQueryDTO.getCurrPage(),operateQueryDTO.getPageSize());
        List<CustomOperateVO> list = operateMapper.getOperateList(page,operateQueryDTO);
        // 创建操作ID和渠道名称的映射关系
        List<Long> operateIds = new ArrayList<>();
        Map<Long, String> operateIdToChannelName = new HashMap<>();
        for (CustomOperateVO customOperateVO : list) {
            Long operateId = customOperateVO.getOperateId();
            String channelName = customOperateVO.getChannelName();
            operateIds.add(operateId);
            operateIdToChannelName.put(operateId, channelName);
        }
        // 根据操作ID批量查询实体对象，并更新渠道类型名称
        if (!operateIds.isEmpty()) {
            List<YxCsCustomOperateEntity> customOperates = operateMapper.selectBatchIds(operateIds);
            for (YxCsCustomOperateEntity customOperateEntity : customOperates) {
                Long operateId = customOperateEntity.getOperateId();
                String channelName = operateIdToChannelName.get(operateId);
                // 设置渠道类型名称并更新数据库
                customOperateEntity.setChannelTypeName(channelName);
                operateMapper.updateById(customOperateEntity);
            }
        }
        // 封装分页结果并返回
        return PageUtils.get(page, list);
    }

    @Override
    public List<YxCsOperatePushCustEntity> findAll() {
        log.info("开始处理【查询所有客户】的业务，无参数");
        return operateMapper.findAll();
    }

    @Override
    public List<YxCsOperatePushCustEntity> findByCustTagId(List<Long> tagIds) {
        log.info("开始处理【根据标签查询客户】的业务，无参数");
        return operateMapper.findByCustTagId(tagIds);
    }

    @Override
    public List<YxCsPushProductEntity> productList() {
        log.info("开始处理【查询商品列表】的业务，无参数");
        return operateMapper.productList();
    }

    @Override
    public List<YxCsPushProductEntity> getProductList(ProductQueryDTO productQueryDTO) {
        log.info("开始处理【条件查询商品列表】的业务，条件参数：{}", productQueryDTO);
        return operateMapper.getProductList(productQueryDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long operateId,Long operateStatus) {
        log.info("开始处理【修改运营状态】的业务，id：{}, 状态值:{}", operateId, operateStatus);
        // 创建客户运营实体对象
        YxCsCustomOperateEntity operate = new YxCsCustomOperateEntity();
        operate.setOperateId(operateId);
        operate.setOperateStatus(operateStatus);
        // 设置运营状态名称
        operate.setOperateStatusName(OPERATE_STATUS[Math.toIntExact(operateStatus)]);
        // 根据ID更新客户运营状态
        operateMapper.updateById(operate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void migrateData(List<Long> operateIds) {
        log.info("开始处理客户运营发送记录】的业务，参数：{}", operateIds);
        // 检查输入参数是否为空
        if (operateIds != null && !operateIds.isEmpty()) {
            // 根据operateIds查询对应的客户运营记录
            List<YxCsCustomOperateEntity> customOperateList = operateMapper.selectBatchIds(operateIds);
            // 创建推送记录实体和推送客户实体
            YxCsOperatePushRecordEntity record = new YxCsOperatePushRecordEntity();
            YxCsOperatePushCustEntity cust = new YxCsOperatePushCustEntity();
            // 遍历每个客户运营记录
            customOperateList.stream().forEach(customOperate -> {
                // 设置推送客户ID、推送状态、错误信息和推送时间
                record.setPushCustId(cust.getPushCustId());
                record.setPushStatus(1);
                record.setErrMsg("");
                record.setPushTime(new Date());
                // 插入推送记录
                recordMapper.insert(record);
            });
        }
    }

}
